package com.itcast.monkey.web.action.common;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.ss.formula.functions.T;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 抽取 Action的公共代码 ，简化开发
 * 
 * @author itcast
 *
 */

@ParentPackage("json-default")
@Scope("prototype")
@Namespace("/")
@Controller
public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T>{
	
	protected T model;
	
	@Override
	public T getModel() {
		return model;
	}

	protected int rows;
	protected int page;
	protected String[] customerIds;
	
	public void setCustomerIds(String[] customerIds) {
		this.customerIds = customerIds;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public BaseAction() {
		Type genericSuperclass = this.getClass().getGenericSuperclass();
		ParameterizedType parameterizedType  = (ParameterizedType) genericSuperclass;
		Type[] types = parameterizedType.getActualTypeArguments();
		Class<T> modelClass = (Class<T>) types[0];
		try {
			model= modelClass.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			System.out.println("模型注入失败");
			e.printStackTrace();
		}
	}
	
	public void pushValueStack(Page<T> pagelist){
		Map<String, Object> result = new HashMap<>();
		result.put("total", pagelist.getTotalElements());
		result.put("rows", pagelist.getContent());
		ActionContext.getContext().getValueStack().push(result);
	}
}
